<template>
  <view class="container">
    <!-- 状态显示 -->
    <view class="status-bar" v-if="serviceStatus">
      <text class="status-text" :class="statusClass">
        {{ getStatusText(serviceStatus) }}
      </text>
    </view>

    <!-- 顶部订单信息 -->
    <view class="order-info">
      <view class="product-card">
        <image 
          :src="order?.product?.image || '/static/default.png'" 
          mode="aspectFill" 
          class="product-image"
        />
        <view class="product-info">
          <text class="product-name">{{ order?.product?.name }}</text>
          <text class="sku-info">{{ order?.productSKUVO?.quantity }}</text>
          <view class="price-quantity">
            <text class="price">¥{{ order?.totalPrice?.toFixed(2) }}</text>
            <text class="quantity">x{{ order?.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 售后申请表单 -->
    <view class="form-section">
      <!-- 售后类型选择 -->
      <view class="form-item">
        <text class="label">售后类型</text>
        <view class="type-options">
          <view 
            v-for="type in serviceTypes" 
            :key="type.value"
            class="type-item"
            :class="{ active: formData.serviceType === type.value }"
            @tap="selectType(type.value)"
          >
            <text class="type-text">{{ type.label }}</text>
          </view>
        </view>
      </view>

      <!-- 售后原因 -->
      <view class="form-item">
        <text class="label">售后原因</text>
        <textarea
          v-model="formData.serviceReason"
          class="reason-input"
          placeholder="请详细描述您的售后原因"
          maxlength="200"
        />
        <text class="word-count">{{ formData.serviceReason.length }}/200</text>
      </view>

      <!-- 图片上传 -->
      <view class="form-item">
        <text class="label">上传凭证</text>
        <view class="upload-section">
          <view 
            v-for="(image, index) in uploadedImages" 
            :key="index" 
            class="image-item"
          >
            <image :src="image" mode="aspectFill" class="preview-image"/>
            <view class="delete-btn" @tap="deleteImage(index)">
              <text class="delete-icon">×</text>
            </view>
          </view>
          <view 
            class="upload-btn" 
            @tap="chooseImage"
            v-if="uploadedImages.length < 3"
          >
            <image src="/static/upload.png" mode="aspectFit" class="upload-icon"/>
            <text class="upload-text">上传图片</text>
          </view>
        </view>
        <text class="upload-tip">最多上传3张图片，支持jpg/png格式</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="footer">
      <button 
        class="submit-btn"
        :disabled="!isFormValid || submitting"
        @tap="submitAfterSales"
      >
        {{ submitting ? '提交中...' : '提交申请' }}
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { addAfterSalesServiceUsingPost } from '@/backend/afterSalesServiceController';
import type { API } from '@/backend/typings';
import { BASE_URL } from '@/baseUrl';
import { uploadFileUsingPost } from '@/backend/fileController';

// 售后类型选项
const serviceTypes = [
  { label: '仅退款', value: 'refund' },
  { label: '退货', value: 'return' },
  { label: '换货', value: 'exchange' }
];

// 表单数据
const formData = ref({
  orderId: undefined as number | undefined,
  serviceType: 'refund',
  serviceReason: '',
  serviceImages: ''
});

const order = ref<API.OrderVO>();
const uploadedImages = ref<string[]>([]);
const submitting = ref(false);
const serviceStatus = ref<string | null>(null);

// 表单验证
const isFormValid = computed(() => {
  const isValid = formData.value.serviceType &&
         formData.value.serviceReason.length >= 2 &&
         formData.value.orderId;
  return isValid;
});

// 售后状态文本映射
const statusTextMap = {
  pending: '待处理',
  processing: '处理中',
  completed: '已完成',
  rejected: '已拒绝'
};

// 获取状态显示文本
const getStatusText = (status: string) => {
  return statusTextMap[status as keyof typeof statusTextMap] || '未知状态';
};

// 状态样式类计算
const statusClass = computed(() => {
  const statusMap = {
    pending: 'status-pending',
    processing: 'status-processing',
    completed: 'status-completed',
    rejected: 'status-rejected'
  };
  return statusMap[serviceStatus.value as keyof typeof statusMap] || '';
});

// 选择售后类型
const selectType = (type: string) => {
  formData.value.serviceType = type;
};

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 3 - uploadedImages.value.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    });

    // 使用统一上传方法
    for (const tempFile of res.tempFilePaths) {
      // @ts-ignore
      const uploadRes = await uploadFileUsingPost(
        { filePath: tempFile },
        { biz: 'afterSalesServiceImg' }  // 修改biz参数
      );

      if (uploadRes.code === 0) {
        // @ts-ignore
        uploadedImages.value.push(uploadRes.data);
        formData.value.serviceImages = uploadedImages.value.join(',');
      } else {
        uni.showToast({
          title: uploadRes.message || '上传失败',
          icon: 'none'
        });
      }
    }
  } catch (error) {
    console.error('上传图片失败：', error);
    uni.showToast({
      title: '上传图片失败',
      icon: 'none'
    });
  }
};

// 删除图片
const deleteImage = (index: number) => {
  uploadedImages.value.splice(index, 1);
  formData.value.serviceImages = uploadedImages.value.join(',');
};

// 提交售后申请
const submitAfterSales = async () => {
  // 表单验证
  if (!formData.value.serviceType) {
    uni.showToast({
      title: '请选择售后类型',
      icon: 'none'
    });
    return;
  }
  
  if (formData.value.serviceReason.length < 2) {
    uni.showToast({
      title: '请填写至少2个字的售后原因',
      icon: 'none'
    });
    return;
  }

  if (!formData.value.orderId) {
    uni.showToast({
      title: '订单信息无效',
      icon: 'none'
    });
    return;
  }

  submitting.value = true;
  try {
    const res = await addAfterSalesServiceUsingPost({
      orderId: formData.value.orderId!,
      serviceType: formData.value.serviceType,
      serviceReason: formData.value.serviceReason,
      serviceImages: formData.value.serviceImages || undefined
    });
    
    if (res.code === 0) {
      uni.showToast({
        title: '申请提交成功',
        icon: 'success'
      });
      
      // 延迟返回，确保用户看到成功提示
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      }, 1500);
    } else {
      uni.showToast({
        title: res.message || '提交失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('提交售后申请失败：', error);
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    });
  } finally {
    submitting.value = false;
  }
};

// 页面加载
onLoad((options: any) => {
  if (options.order) {
    try {
      order.value = JSON.parse(decodeURIComponent(options.order));
      formData.value.orderId = order.value?.id;
    } catch (error) {
      console.error('解析订单信息失败：', error);
      uni.showToast({
        title: '订单信息错误',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  } else {
    uni.showToast({
      title: '缺少订单信息',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.order-info {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.product-card {
  display: flex;
  gap: 20rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  background: #f5f5f5;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  line-height: 1.4;
}

.sku-info {
  font-size: 24rpx;
  color: #999;
  margin: 8rpx 0;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 32rpx;
  color: #ff5722;
  font-weight: 600;
}

.quantity {
  font-size: 26rpx;
  color: #999;
}

.form-section {
  background: #fff;
  padding: 30rpx;
}

.form-item {
  margin-bottom: 40rpx;
}

.label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
  display: block;
}

.type-options {
  display: flex;
  gap: 20rpx;
}

.type-item {
  flex: 1;
  height: 80rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.type-item.active {
  background: #fff2ed;
  border-color: #ff5722;
}

.type-text {
  font-size: 28rpx;
  color: #666;
}

.type-item.active .type-text {
  color: #ff5722;
}

.reason-input {
  width: 100%;
  height: 200rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.word-count {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  margin-top: 8rpx;
}

.upload-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  width: 160rpx;
  height: 160rpx;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.delete-btn {
  position: absolute;
  top: -16rpx;
  right: -16rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  color: #fff;
  font-size: 32rpx;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.upload-icon {
  width: 48rpx;
  height: 48rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 16rpx;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 40rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.submit-btn:disabled {
  opacity: 0.6;
}

/* 状态栏样式 */
.status-bar {
  padding: 10px 20px;
  background-color: #fff;
  margin-bottom: 10px;
}

.status-text {
  font-size: 14px;
  font-weight: bold;
}

.status-pending {
  color: #ff9800;
}

.status-processing {
  color: #2196f3;
}

.status-completed {
  color: #4caf50;
}

.status-rejected {
  color: #f44336;
}
</style> 